// const ws = new WebSocket("ws://localhost:1001")

// const socket = io()

// socket.on('connect',() =>{
//     console.log("连接成功")
// })

// // ws.addEventListener('open',() =>{
// //     console.log("连接上服务器了");
// //     ws.send("hello")
// // })

// ws.addEventListener('message',(event) =>{
//     console.log(event.data);
// })

$(function () {

    const socket = io("http://localhost:3001")
    let userName = ''

    //当前时间
    console.log();

    $('.chatJoinBtn').click(() => {
        if ($('.NameInput input').val() == '') {
            alert('请输入昵称')
            return
        } else {
            $('.chaNews').css('display', 'none')
            $('.chatting').css('display', 'block')

            userName = $('.NameInput input').val()
        }

    })

    $('.SendBtn').click(() => {
        let message = $('.chattingBottom input').val()
        $('.chattingBottom input').val(' ')
        socket.emit('chat message', {
            Name: userName,
            msg: message,
            time: new Date().getHours() + ':' + new Date().getMinutes() + ':' + new Date().getSeconds()
        });

        
    })

    socket.on('chat message', msg => {
        
        
        if (msg.Name == userName) { //表示是自己发送
            let html = `
                <div class="own">
                   <div class="xinxi">
                        <p>${msg.msg}</p>
                         <p><span class="UserName">${msg.Name}</span><span class="time">${msg.time}</span></p>
                    </div>
                    <div class="Touxiang">
                        <img src="./img/用户.png" alt="">
                   </div>
                </div>
            `

            $('.chattingCon').append(html)
        } else { //表示是别人发送
            let html = `
                <div class="adverse">
                    <div class="Touxiang">
                        <img src="./img/用户.png" alt="">
                    </div>
                     <div class="xinxi">
                        <p>${msg.msg}</p>
                        <p><span class="UserName">${msg.Name}</span><span class="time">${msg.time}</span></p>
                    </div>
                </div>
            `
            $('.chattingCon').append(html)
        }

        $('.chattingCon')[0].scrollTop = $('.chattingCon')[0].scrollHeight + 100;
    })
    // 发送消息到服务器  

})


